package hydrap2p.gui.commands;

import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import hydrap2p.download.DownloadPriority;
import hydrap2p.download.Source;
import hydrap2p.gui.FileTransferPanel;
import hydrap2p.gui.GUIDataHandler;
import hydrap2p.gui.GUIDownloadListing;
import hydrap2p.gui.SearchPanel;
import hydrap2p.library.HashData;
import hydrap2p.search.SearchResult;

public class Cmd_SearchPanel_AddResultToDownloadQueue implements Command {

	@Override
	public void execute() {
		// Put selected indices in a sortable list
		int[] indices = SearchPanel.getInstance().getTable().getSelectedRows();
		
		// For each row, generate a download listing
		GUIDownloadListing gdl;
		SearchResult sr;
		String name;
		String protocol;
		String hashes = "";
		String status = GUIDownloadListing.PAUSED;
		
		int priority;
		int priorityCount = 0;
		long size;
		for(int i : indices){
			
			priorityCount++;
			
			sr = SearchPanel.getInstance().getCurrentResults().get(i);
			
			name = sr.getNames().get(0);
			protocol = sr.getSources().get(0).getProtocol();
			for(HashData hd : sr.getHashes()){
				hashes += "; ";
				hashes += hd.getHashdata();
				hashes += " [" + hd.getAlgorithm() + "]";
			}
			hashes = hashes.substring(2);
			priority = FileTransferPanel.getInstance().getTable().getModel().getRowCount() + priorityCount;
			size = sr.getSize();
			
			// JFileChooser
			JFileChooser chooser = new JFileChooser();
			boolean sel;
			File filePath = null;
			
			do{
				sel = true;
				chooser.setDialogTitle("Select destination for " + name);
				chooser.setCurrentDirectory(new File("./"));
				chooser.setMultiSelectionEnabled(false);
				
				int chooserStatus = chooser.showDialog(null,"Save");
				
				try{
					while(filePath == null){
						if(chooserStatus == JFileChooser.CANCEL_OPTION){
							return;
						}
						if(chooserStatus == JFileChooser.APPROVE_OPTION){
							if(chooser.getSelectedFile().exists()){
								JOptionPane.showMessageDialog(null, "The specified file already exists.\n\nPlease select a different filepath.");
								chooserStatus = chooser.showDialog(null,"Save");
							}
						}
						filePath = chooser.getSelectedFile();
						// Check filepath
						if(filePath.getName().length() == 0){
							JOptionPane.showMessageDialog(null, "No filename entered.");
							filePath = null;
						}else if(filePath.getParent() == null){
							JOptionPane.showMessageDialog(null, "Invalid directory.");
							filePath = null;
						}
					}
					
				}catch(Exception ex){
					sel = false;
					
				}
			}while(!sel);
			
			System.out.println("File selected.");
			
			// Find allowable number of sources (too many overloads the system)
			int allowableSources = (int)Math.min(10, sr.getSourcesSize());
			
			//gdl = new GUIDownloadListing(filePath.getName(), protocol, hashes, status, filePath.toString(), 1, 0, priority, size, 0, 0);
			gdl = new GUIDownloadListing(filePath.getName(), protocol, hashes, status, filePath.toString(), allowableSources, 0, DownloadPriority.NORMAL, size, 0, 0);
			
			for( String filename : sr.getFilenames()){
				gdl.addContent(filename);
			}
			
			//for( Source source : sr.getSources()){
			//	gdl.addSource(source);
			//}
			for(int s = 0; s < allowableSources; s++){
					gdl.addSource(sr.getSources().get(s));
			}
			
			
			GUIDataHandler.getInstance().addToDownloadListing(gdl);	
		}
		
		// Refresh data transfer table
		FileTransferPanel.getInstance().refreshDownloadList();
		
		System.out.println(getCommand());
		
	}

	@Override
	public String getCommand() {
		return this.getClass().getSimpleName();
	}

	@Override
	public void unexecute() {
		// TODO Auto-generated method stub

	}

}
